package in.hitmedia.test.sort;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class QuickSort 
{

	private Long[] read(String filename) throws IOException
	{
		
		BufferedReader br = new BufferedReader(new FileReader(filename));
		
		String line = null;
		
		List<Long> a = new ArrayList<Long>();
		while((line = br.readLine()) != null)
		{
			try
			{
				long parseLong = Long.parseLong(line.trim());
				a.add(parseLong);
			}
			catch (NumberFormatException nfe)
			{
				
			}
		}
		
		return a.toArray(new Long[a.size()]); 
	}
	
	
	
	private int partion(Long a[],int start, int end)
	{
		Long p = a[start];
		int i = start;
		for(int j=start+1; j<= end; ++j)
		{
			if(a[j] < p)
			{
				i++;
				exchange(a, i, j);
				//print(a);
			}
			
		}
		exchange(a, start, i);
		return i;
		
	}



	private void exchange(Long[] a, int i, int j) 
	{
		Long tmp=a[j];
		a[j]=a[i];
		a[i]= tmp;
	}
	
	private void quickSort(Long a[], int start, int end)
	{
		
		if ( end > start)
		{
			int p = partion(a, start, end);
			quickSort(a, start, p-1);
			quickSort(a, p+1, end);
		}
	}
	
	private static void print(Long a[])
	{
		for(int i=0; i < a.length; ++i)
		{
			System.out.print(a[i]+"\t");
			if ((i+1) %10 == 0)
			{
				System.out.println();
			}
		}
		System.out.println();
	}
	
	
	//Find the k-th smallest element
	private Long select(Long a[], int k)
	{
		int i = 0;
		int j = a.length-1;
		
		while (j > i)
		{
			int p = partion(a, i, j);
			if ( p < k )
			{
				i=p+1;
			}
			else if (p > k )
			{
				j=p-1;
			}
			else return a[k];
		}
		
		return a[k];
	}
	
	public void runQuickSort (String in, String out)
	{
		try
		{
			//Long[] inArray = read(in);
			
			Long inArray[] = new Long[] {6L, 7L, 9L , 1L, 2L ,5L, 18L, 21L};
			//Long inArray[] = new Long[] {9L, 8L, 7L , 6L, 5L ,4L, 3L, 2L};
			//print(inArray);
			
			System.out.println(select(inArray, 1));
			
			long start = System.currentTimeMillis();
			
			quickSort(inArray, 0, inArray.length-1);
			long end = System.currentTimeMillis();
			
			System.out.println("Time to process "+((end - start)) +" miliseconds.");
			
			BufferedWriter bw = new BufferedWriter(new FileWriter(out));
			
			for (int i = 0; i < inArray.length; ++i)
			{
				bw.write(""+inArray[i]);
				bw.newLine();
			}
			bw.close();
			
			print(inArray);
		}
		catch (Exception e)
		{
			System.out.println("Received exception"+ e);
		}
		
		
	}
	
	public static void main(String args[])
	{
		QuickSort qs = new QuickSort();
		qs.runQuickSort(args[0], args[1]);
	}
	
}
